package com.kly.manager.upload;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.kly.config.CosClientConfig;
import com.kly.domain.dto.file.UploadPictureResult;
import com.kly.manager.CosManager;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;

/**
 * @author admin
 * @date 2025/3/3
 */
@Slf4j
@Component
public abstract class PictureUploadTemplate {

    /**
     * 单张图片最大为 2M
     */
    protected static final long ONE_M = 1024 * 1024L;

    /**
     * 文件格式信息
     */
    protected static final List<String> IMAGE_FORMATS = Arrays.asList("jpg", "jpeg", "png", "gif", "bmp", "webp");

    @Resource
    private COSClient cosClient;

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;


    // 将本地文件上传到 COS
    public UploadPictureResult uploadFile(Object inputSource, String uploadPathPrefix) {
        // 校验图片
        validatePictureInfo(inputSource);
        // 文件重命名
        String uploadPath = String.format("%s/%s", uploadPathPrefix, renameFile(getOriginalName(inputSource)));
        // 上传文件

        //     获取文件名
        File tempFile = null;
        try {
            //     创建临时文件
            tempFile = File.createTempFile(uploadPath, "");
            tempFile = processFile(inputSource, tempFile);
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, tempFile);

            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            // 获取处理后的图片信息
            List<CIObject> ciObjectList = putObjectResult.getCiUploadResult().getProcessResults().getObjectList();
            if (CollUtil.isNotEmpty(ciObjectList)) {
                CIObject ciObject = ciObjectList.get(0);
                CIObject thumbnailObject = ciObject;
                if (ciObjectList.size() > 1) {
                    thumbnailObject = ciObjectList.get(1);
                }
                // 获取主色调
                String picColor = imageInfo.getAve();
                UploadPictureResult uploadPictureResult = getCompressedPictureResult(ciObject, tempFile, thumbnailObject, picColor);
                // 设置原始地址
                String originalUrl = cosClientConfig.getHost() + "/" + uploadPath;
                uploadPictureResult.setOriginalUrl(originalUrl);
                return uploadPictureResult;
            }
            UploadPictureResult uploadPictureResult = getUploadPictureResult(imageInfo, uploadPath, tempFile);
            return uploadPictureResult;
            //     上传文件到 COS
        } catch (Exception e) {
            log.error("上传文件失败", e);
        } finally {
            if (tempFile != null) {
                tempFile.delete();
            }
        }

        return null;
    }

    private UploadPictureResult getCompressedPictureResult(CIObject ciObject, File tempFile, CIObject thumbnailObject, String picColor) {
        // 求scale
        int height = ciObject.getHeight();
        int width = ciObject.getWidth();
        long size = ciObject.getSize().longValue();
        double scale = NumberUtil.round(width * 1.0 / height, 2).doubleValue();
        // 设置图片信息
        String thumbnailUrl = String.format("%s/%s", cosClientConfig.getHost(), thumbnailObject.getKey());

        UploadPictureResult uploadPictureResult = UploadPictureResult.builder()
                .url(cosClientConfig.getHost() + "/" + ciObject.getKey())
                .picSize(size)
                .picName(tempFile.getName())
                .picWidth(width)
                .picHeight(height)
                .picScale(scale)
                .picFormat(ciObject.getFormat())
                .thumbnailUrl(thumbnailUrl)
                .picColor(picColor)
                .build();
        return uploadPictureResult;
    }

    private UploadPictureResult getUploadPictureResult(ImageInfo imageInfo, String uploadPath, File tempFile) {
        // 求scale
        int height = imageInfo.getHeight();
        int width = imageInfo.getWidth();
        long size = (long) imageInfo.getQuality();
        double scale = NumberUtil.round(width * 1.0 / height, 2).doubleValue();
        // 设置图片信息

        UploadPictureResult uploadPictureResult = UploadPictureResult.builder()
                .url(cosClientConfig.getHost() + "/" + uploadPath)
                .picSize(size)
                .picName(tempFile.getName())
                .picWidth(width)
                .picHeight(height)
                .picScale(scale)
                .picFormat(imageInfo.getFormat())
                .picColor(imageInfo.getAve())
                .build();
        return uploadPictureResult;
    }

    protected abstract File processFile(Object inputSource, File tempFile);

    protected abstract String getOriginalName(Object inputSource);

    protected abstract void validatePictureInfo(Object inputSource);


    /**
     * 文件重命名
     */
    private String renameFile(String fileName) {
        // 取后缀
        String suffix = FileUtil.getSuffix(fileName);
        // 生成唯一文件名
        String uuid = RandomUtil.randomString(16);

        return String.format("%s_%s.%s", LocalDate.now(), uuid, suffix);
    }
}
